import mysql.connector
from mysql.connector import Error
import pandas as pd

def connect_to_database():
    try:
        # 替换这些变量为你自己的数据库信息
        connection = mysql.connector.connect(
            host='192.168.198.128',  # 确保 IP 地址正确
            port=23306,              # 确保端口号正确
            database='ry-vue',
            user='root',
            password='123456'
        )
        
        if connection.is_connected():
            print("成功连接到 MySQL 数据库")
            
            # 创建游标对象
            cursor = connection.cursor()
            
            # 执行 SQL 查询
            cursor.execute("SELECT * FROM `ry-vue`.`sys_notice` LIMIT 0,1000")
            # 获取查询结果
            results = cursor.fetchall()
            
            # 获取列名
            column_names = [desc[0] for desc in cursor.description]
            
            # 将结果转换为 DataFrame
            df = pd.DataFrame(results, columns=column_names)
            
            # 打印 DataFrame
            print(df[:1])
            
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL 连接已关闭")

if __name__ == "__main__":
    connect_to_database()



